# 功能实现模型来源
# hyperlpr3在树莓派上可能无法安装 https://github.com/szad670401/HyperLPR?tab=readme-ov-file
# https://github.com/szad670401/HyperLPR/tree/v1
import cv2
# import hyperlpr3 as lpr3
from hyperlpr import *
from PIL import Image
from flask import request, url_for, render_template, redirect, Blueprint, current_app
from my_util import Logger, copy_file, delete_files
import os
import random

# initialize our Flask application and the lpr object
blueprint = Blueprint('processPlatNoImg', __name__)

lprObject = None
loger = Logger()
default_pic_name = "defaultPlate.jpg"

def init_default_source():
    # 删除多余的图片
    max_files_allowed = 30 #后续拷贝一个默认图片，加上上传图片，实际文件夹当中有32个文件
    delete_files(current_app.config['UPLOAD_FOLDER'], max_files_allowed)
    # 默认图片拷贝
    source_path = os.path.join(current_app.config['SOURCE_FOLDER'], default_pic_name)
    dest_path = os.path.join(current_app.config['UPLOAD_FOLDER'], default_pic_name)
    if not os.path.exists(dest_path) or not os.path.isfile(dest_path):
        copy_file(source_path, dest_path)

# Instantiate object
def load_object():
    # 默认图片拷贝
    source_path = os.path.join(current_app.config['SOURCE_FOLDER'], default_pic_name)
    dest_path = os.path.join(current_app.config['UPLOAD_FOLDER'], default_pic_name)
    copy_file(source_path, dest_path)
    global lprObject
    lprObject = HyperLPR_plate_recognition

'''
def load_object3():
    # 默认图片拷贝
    source_path = os.path.join(current_app.config['SOURCE_FOLDER'], default_pic_name)
    dest_path = os.path.join(current_app.config['UPLOAD_FOLDER'], default_pic_name)
    copy_file(source_path, dest_path)
    global lprObject
    lprObject = lpr3.LicensePlateCatcher()
'''

def prepare_image(image):
    loger.debug("Preparing image"+image)
    image = cv2.imread(image)
    return image

def crop_image(image1, image2, x1, y1, x2, y2):
    # 打开图片
    img = Image.open(image1)
    # 截取图片，参数为左上角和右下角的坐标
    cropped_img = img.crop((x1, y1, x2, y2))
    # 保存截取的图片
    cropped_img.save(image2)
    
    loger.debug("recognize plateNo: " + image2)

@blueprint.route('/plateReg', methods=['GET', 'POST'])  # 访问的路径
def process_plateReg():
    init_default_source()
    data = {"success": "未上传"}
    title = "Upload an image"
    name = default_pic_name
    if request.method == "POST":
        if request.files.get("image"):

            image1 = request.files["image"]
            imagePath = os.path.join(current_app.config['UPLOAD_FOLDER'], image1.filename)
            image = image1.save(imagePath)
            loger.debug("接受车牌图片路径"+imagePath)

            processed_image = prepare_image(imagePath)

            data["predictions"] = []
            
            '''
            try:
                if lprObject == None:
                    load_object3()
                    loger.info("lpr object not initialzed")
                lpr3_results = lprObject(processed_image)
            except Exception as e:
                print("Exception  load hyperlpr3", e)
            '''
                
            try:
                if lprObject == None:
                    load_object()
                    loger.info("lpr object not initialzed")
                lpr_results = lprObject(processed_image)
            except Exception as e:
                print("Exception load hyperlpr", e)
                lpr_results = ""

            if len(lpr_results):
                print("lpr_results:")
                print(lpr_results[0])
                
                result = lpr_results[0]
                # image2Name = "outputPlatNo"
                image2Name = result[0] + ".jpg"
                image2 = os.path.join(current_app.config['UPLOAD_FOLDER'], image2Name)
                    
                crop_image(imagePath, image2, result[2][0], result[2][1], result[2][2], result[2][3])
                
                r = {"label": result[0], "probability": int(100*result[1])}
            else:
                image2Name = image1.filename
                r = {"label": "unkonw", "probability": int(0)}

            data["predictions"].append(r)

            # indicate that the request was a success
            data["success"] = "已上传"
            title = "predict"

            return render_template('plateNoReg.html', data=data, title=title, name=image2Name)
    return render_template('plateNoReg.html', data=data, title=title, name=name)